/**
 * Created by Edwin on 2015/12/17 0017.
 */



//主要针对删除操作
function angularHttpGet($http,url,callBack){
    $http.get(url).success(function(result){
        $('.modal').each(function(i){
            $(this).modal("hide");
        });
        if(result == 'success'){
            callBack(result);
        }else{
            $.tipsShow({ message : result, type : 'warning' });
        }
    })
}

function initPageInfo($scope){
    $("#dataLoading").removeClass("hide");
    $scope.selectPage = [
        {name:'10',value : '10'},
        {name:'20',value : '20'},
        {name:'30',value : '30'}
    ];
    $scope.limitNum = '10';
    $scope.currentPage = 1;
    $scope.totalPage = 1;
    $scope.totalItems = 1;
    $scope.limit = 10;
    $scope.pages = [];
    $scope.startNum = 1;
    $scope.keywords = $('#searchInput').val();
    $scope.startDate=$('#startDate').val();
    $scope.endDate=$('#endDate').val();
    $scope.area = $('#pageArea').val();
}



function getAutoComplete($scope,$http,keyName,callback){
    $http.get("/admin/manage/getDocumentList/"+keyName+"?limit=1000&currentPage=1").success(function(result){
        var cailiao=[];
        for(var i in result.docs){
            var t={};
            result.docs[i]["hex"]="#EFDECD";
            result.docs[i]["label"]=result.docs[i].name;
            result.docs[i]["rgb"]="(239, 222, 205)";
            cailiao.push( result.docs[i]);
            if( $scope.formData.cashFlowType==0&&!$scope.targetID){
                addPurchaseItem(result.docs[i]._id,result.docs[i].name,result.docs[i].price,1,1);
            }
        }
        $('#nope').autocompleter({
            highlightMatches: true,
            source: cailiao,
            template: '{{ name }}',
            hint: true,
            empty: false,
            limit: 5,
            callback: function (value, index, selected) {
                if (selected) {
                    $("#nope").val("");
                    addPurchaseItem(selected._id, selected.name,selected.price,1,1);
                    if(callback)
                        callback();
                }
            }
        });

    });
}

//切换资金流动类型
function swithCashType($scope,$http,id,type){
    // 清空列表
    $("#columnTr").remove();
    $(".datatr").remove();
    var template=getColumnStrByType($scope.formData.cashFlowType);
    var qobje = $(template);
    countTotal();
    $("#cart").find(".counttr").before(qobje);
    $('#nope').autocompleter('destroy');
    if(type==0){//新增操作，默认加载销售数据
        getAutoComplete($scope,$http,"setmeal");
    }else if(type==1){
        getAutoComplete($scope,$http,"ingredient");
    }
}

//根据资金流动类型获取表头
function getColumnStrByType(type){
    var reStr="";
    var columnNames=null;
    reStr=reStr+"<tr id='columnTr'>";
    if(type==0){
        columnNames=new Array("名称","数量","价格","总计");
    }else if(type==1){
        columnNames=new Array("名称","数量","价格","总计");
    }else{
        columnNames=new Array("名称","数量","价格","总计");
    }
    for( var i in columnNames ){
        reStr=reStr+"<th width='20%'>"+columnNames[i]+"</th>";
    }
    reStr=reStr+"</tr>";
    return reStr;
}

function addPurchaseItem(id, name, gprice,count,type) {
    var template1="";
    if($(".datatr[itemname="+name+"]").length>0){
        return;
    }
    var template ="";
    template = "<tr class='datatr' itemid='"
        + id
        + "' itemname='"
        + name
        + "'> "
        + " <td>"
        + name
        + "</td>"
        + " <td><input type='number' style='width:50px' value='" + (count != null ? count : 1) + "' class='sl banSty'/></td>"
        + " <td style='cursor:pointer;color: red;font-weight: bold;' >" +
        "￥<span class='dj' onclick='changeVal(this)'>"
        + gprice
        + "</span></td>"
        + " <td  style='color: red;font-weight: bold;'>￥<span class='zj'>0.00</span></td>"
        + " <td class='viewSty'><i class='fa fa-minus-circle'  style='cursor:pointer;' onclick='removePurchaseItem(\""
        + id + "\")'></i></td>" + " </tr>";

    var qobje = $(template);
    $("#cart").find(".counttr").before(qobje)
    priceSyn(qobje);
}

function priceSyn(obj) {
    var p = /^[1-9](\d+(\.\d{1,4})?)?$/;
    var p1 = /^[0-9](\.\d{1,4})?$/;
    var reg = /^[0-9]*[1-9][0-9]*$/;
    var dj = obj.find(".dj").html();
    var sl = obj.find(".sl").val();
    sl = reg.test(sl) ||sl==""? sl : 1;
    sl = sl <= 0&&sl!=""? 1 : sl;
    dj = (p1.test(dj) || p.test(dj)) ? dj : 0;
    zj = (dj * sl).toFixed(2);
    obj.find(".sl").val(sl);
    obj.find(".dj").val(dj);
    obj.find(".zj").html(zj);
    countTotal();
}

function countTotal() {
    var count = 0;
    $(".zj").each(function() {
        count += parseFloat($(this).html());
    });
    $("#totalcount").html(count.toFixed(2));
}

function addOtherItem(type) {
    var name = $("#nope").val();
    if(name==""){
        alert("不能添加名字为空的项目!")
        return;
    }
    var id = uuid();
    addPurchaseItem(id, name, 1, 1,type);
}

function removePurchaseItem(id) {
    $(".grid-item[itemid='" + id + "']").removeClass("f_in_sel");
    $(".grid-item[itemid='" + id + "']").addClass("f_in");
    $("#cart").find("tr[itemid='" + id + "']").remove();
    countTotal();
}
function changeVal(obj) {
    var cval = prompt("请输入单价", $(obj).html());
    if (cval != null) {
        $(obj).html(cval);
        priceSyn($(obj).parent().parent());
    }
}

// 保存资金流动信息
function saveCashFlow($scope,$http,pageData,isValid){
    var items = [];
    var total=0;
    $("#cart .datatr").each(function() {
        var item={};
        var itemId = $(this).attr("itemid");
        var itemname = $(this).attr("itemname");
        var sl = $(this).find(".sl").val();
        var dj = $(this).find(".dj").html();
        item["id"]=itemId;
        item["name"] = itemname;
        item["sl"] = sl;
        item["price"] = dj;
        items.push(item);
        total=total+sl * dj;
    });
    $scope.formData.price=total;
    $scope.formData.items=items;
    $scope.formData.type=$scope.formData.cashFlowType;
    angularHttpPost($http,isValid,getTargetPostUrl($scope,pageData.bigCategory),$scope.formData,function(data){
            // 进货处理更新记录
                for (var i in items) {
                    if($scope.formData.cashFlowType==1) {
                        var uData = {};
                        uData["name"] = items[i].name;
                        uData["price"] = items[i].price;
                        uData["pid"] = data._id;
                        if (items[i].id.indexOf("-")>0&&$scope.cmode==1) {
                            angularHttpPost($http, isValid, "/admin/manage/ingredient/addOne", uData, function (ingdata) {
                                uData["ig"] = ingdata._id;
                                angularHttpPost($http, isValid, "/admin/manage/ingbuyrecord/addOne", uData);
                            });
                        } else if(items[i].id.indexOf("-") < 0) {
                            angularHttpPost($http, isValid, "/admin/manage/ingredient/modify?uid=" + items[i].id, uData, function (ingdata) {
                                uData["ig"] = ingdata.item[i].id;
                                console.log(uData);
                                //angularHttpPost($http, isValid, "/admin/manage/ingbuyrecord/addOne", uData);
                            });
                        }
                    }else{
                        var uData={};
                        uData["name"]=items[i].name;
                        uData["price"]=items[i].price;
                        console.log(uData);
                        if(items[i].id.indexOf("-")>0&&$scope.cmode==1){
                            angularHttpPost($http, isValid, "/admin/manage/setmeal/addOne", uData);
                        }else if(items[i].id.indexOf("-") < 0){
                            angularHttpPost($http, isValid, "/admin/manage/setmeal/modify?uid=" + items[i].id, uData);
                        }
                    }
                }
        initPagination($scope, $http);
        $(".datatr").remove();
        $scope.formData.name = "";
    });
}

// 保存销售信息
function saveOther($scope,$http){
    var items = [];
    var total=0;
    $("#cart .datatr").each(function() {
        var item={};
        var itemid = $(this).attr("itemid");
        var itemname = $(this).attr("itemname");
        item["ing"] = itemid;
        item["name"] = itemname;
        item["sl"] = sl;
        item["dj"] = dj;
        item["zj"] = (sl * dj).toFixed(2);
        items.push(item);
        total=total+sl * dj;
    });
    $scope.formData.price=total;
    $scope.formData.items=items;
    angularHttpPost($http,isValid,getTargetPostUrl($scope,pageData.bigCategory),$scope.formData,function(data) {
        if (!$scope.formData.targetID) {
            var uData = {};
            uData["price"] = total;
            uData["type"] = 1;
            uData["sid"] = data._id;
            angularHttpPost($http, isValid, "/admin/manage/cashflow/addOne", uData);

        }
        initPagination($scope, $http);
        $(".datatr").remove();
        $scope.formData.name = "";
    });
}



//翻页组件
function getPageInfos($scope,$http,url,reqType){
    $("#dataLoading").removeClass("hide");

    // 定义翻页动作
    $scope.loadPage = function(page){
        $scope.currentPage = page;
        getPageInfos($scope,$http,url)
    };

    $scope.nextPage = function () {
        if ($scope.currentPage < $scope.totalPage) {
            $scope.currentPage++;
            getPageInfos($scope,$http,url);
        }
    };

    $scope.prevPage = function () {
        if ($scope.currentPage > 1) {
            $scope.currentPage--;
            getPageInfos($scope,$http,url);
        }
    };

    $scope.changeOption = function(){
        $scope.limit = Number($scope.limitNum);
        getPageInfos($scope,$http,url);
    };


    $http.get(url+"?limit="+$scope.limit+"&currentPage="+$scope.currentPage+"&searchKey="+$scope.keywords+"&startDate="+$scope.startDate+"&endDate="+$scope.endDate).success(function(result){
        console.log("getData success!");
        $scope.data = result.docs;
        $scope.pay =result.pay;
        $scope.totalPrice=result.totalPrice;
        $scope.ingredienttypes= result.ingredienttypes;
        $scope.cuisinetypes= result.cuisinetypes;
        $scope.cashFlowTypes= result.cashFlowTypes;
        if(result.pageInfo){
            $scope.totalItems = result.pageInfo.totalItems;
            $scope.currentPage = result.pageInfo.currentPage;
            $scope.limit = result.pageInfo.limit;
            $scope.startNum = result.pageInfo.startNum;
            //获取总页数
            $scope.totalPage = Math.ceil($scope.totalItems / $scope.limit);
            //生成数字链接
            var pageNum =  Number($scope.currentPage);
            if ($scope.currentPage > 1 && $scope.currentPage < $scope.totalPage) {
                $scope.pages = [
                    $scope.currentPage - 1,
                    $scope.currentPage,
                    $scope.currentPage + 1
                ];
            }
            else if ($scope.currentPage == 1 && $scope.totalPage == 1) {
                $scope.pages = [
                    $scope.currentPage
                ];
            }
            else if ($scope.currentPage == 1 && $scope.totalPage > 1) {
                $scope.pages = [
                    $scope.currentPage,
                    $scope.currentPage + 1
                ];
            } else if ($scope.currentPage == $scope.totalPage && $scope.totalPage > 1) {
                $scope.pages = [
                    $scope.currentPage - 1,
                    $scope.currentPage
                ];
            }
            $(".datashow").show();
        }else{
            console.log("获取分页信息失败")
        }

        $("#dataLoading").addClass("hide");

    })
}

//初始化删除操作
function initDelOption($scope,$http,info){

    // 单条记录删除
    $scope.delOneItem = function(id){
        initCheckIfDo($scope,id,info,function(currentID){
            angularHttpGet($http,"/admin/manage/"+$('#currentCate').val()+"/del?uid="+currentID,function(){
                initPagination($scope,$http);
            });
        });
    };

    $scope.getNewIds = function($event){
        if($event){
            $event.stopPropagation();
        }
        getSelectIds();
    };

    // 批量删除
    $scope.batchDel = function(){
        var targetIds = $('#targetIds').val();
        if(targetIds && targetIds.split(',').length > 0){
            initCheckIfDo($scope,$('#targetIds').val(),info,function(currentID){
                angularHttpGet($http,"/admin/manage/"+$('#currentCate').val()+"/batchDel?ids="+currentID+"&expandIds="+$('#expandIds').val(),function(){
                    initPagination($scope,$http);
                });
            });
        }else{
            alert('请至少选择一项')
        }
    }
}



//提示用户操作窗口
function initCheckIfDo($scope,targetId,msg,callBack){
    $('#checkIfDo').on('show.bs.modal', function (event) {
        if(targetId){
            $scope.targetID = targetId;
        }
        $(this).find('.modal-msg').text(msg);
    }).on('hide.bs.modal', function (event) {
        $scope.targetID ="";
    });
    $('#checkIfDo').modal('show');
    //确认执行删除
    $scope.confirmDo = function (currentID) {
        callBack(currentID);
    };
}



//初始化普通列表分页
function initPagination($scope,$http){
    initPageInfo($scope);
    getPageInfos($scope,$http,"/admin/manage/getDocumentList/"+$('#currentCate').val(),'normalList');
}

//获取添加或修改链接
function getTargetPostUrl($scope,bigCategory){
    var url = "/admin/manage/"+bigCategory+"/addOne";
    if($scope.targetID){
        url = "/admin/manage/"+bigCategory+"/modify?uid="+$scope.targetID;
    }
    return url;
}






